<!--
 * @Descripttion: 采购分支管理
 * @version:
 * @Author: 张文韬
 * @Date: 2020-10-13 11:49:35
 * @LastEditors: 穆宏宇
 * @LastEditTime: 2020-11-26 17:52:57
-->
<template>
  <el-card class="box-card">
    <!-- table 数据表格 START -->
    <e-table :data="tableData"
             :columns="columns"
             stripe
             border
             :maxHeight="tableMaxHeight"
             style="width: 100%"
             :current="pageData.pageNum"
             :total="pageData.total"
             @page-size-change="changePageSize"
             @page-current-change="changePageCurrent">
      <template slot-scope="{scope}"
                slot="operation">
        <!-- <el-button @click="resetBasicInfo(scope.row)"
                   type="primary"
                   size="mini"
                   plain>修改基本信息</el-button>
        <el-button @click="handleEditProcessInfo(scope.row)"
                   type="warning"
                   size="mini"
                   plain>编辑流程信息</el-button> -->
        <el-button @click="handleCatalogueSetting(scope.row)"
                   type="danger"
                   size="mini"
                   :disabled="scope.row.purchaseType==='2'"
                   plain>目录设置</el-button>
      </template>
    </e-table>
    <!-- table 数据表格 END -->
    <!-- editDialog 修改基本信息弹窗 START -->
    <el-dialog :title="editDialogTitle"
               :visible.sync="editInfoDialogShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               @close="cancelDialogDataHandle"
               width="50%">
      <e-form ref="dialogForm"
              :form-options="editForm"
              :form-label-width="editFormLabelWidth"
              :form-rules="editFormRules"
              :form-data-current="dialogFormCurrent"></e-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="cancelDialogDataHandle">取 消</el-button>
        <el-button type="primary"
                   @click="saveDialogDataHandle">确 定</el-button>
      </span>
    </el-dialog>
    <!-- editDialog 修改基本信息弹窗 END -->
    <!-- editDialog 编辑流程信息弹窗 START -->
    <el-dialog :title="editDialogTitle"
               :visible.sync="editProcessDialogShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               @close="cancelDialogDataHandle"
               width="50%">
      <el-row class="dialog-box">
        <el-col :span="24">
          <el-col :span="12"><div>属性名称</div></el-col>
          <el-col :span="6"><div>是否有该流程</div></el-col>
          <el-col :span="6"><div>流程是否自动</div></el-col>
        </el-col>
        <el-col class="item-box" :span="24" v-for="(item, index) in processData" :key="index">
          <el-col :span="12"><div>{{ item.optional1 }}</div></el-col>
          <el-col :span="6">
            <el-switch v-model="item.dictionaryKey3"
                       active-value='1'
                       inactive-value="0"
                       @change="switchProcessChange(item)"></el-switch>
          </el-col>
          <el-col :span="6">
            <el-switch v-if="item.dictionaryKey4==='1'"
                       v-model="item.optional2"
                       active-value='1'
                       inactive-value="0"
                       @change="switchProcessChange(item)"></el-switch>
          </el-col>
        </el-col>
      </el-row>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="cancelDialogDataHandle">取 消</el-button>
        <el-button type="primary"
                   @click="submmitEditProcess">确 定</el-button>
      </span>
    </el-dialog>
    <!-- editDialog 编辑流程信息弹窗 END -->
    <!-- editDialog 目录设置弹窗 START -->
    <el-dialog :title="editDialogTitle"
               :visible.sync="editCatalogueDialogShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               @close="cancelDialogDataHandle"
               width="50%">
      <el-row style="margin: 0 30px">
        <el-col :span="4"><span>查询范围</span></el-col>
        <el-col :span="12">
          <el-radio-group v-model="isQueryAll" @change="handleSelectQueryAll">
            <el-radio :label="0" >仅显示已设置</el-radio>
            <el-radio :label="1">显示全部</el-radio>
          </el-radio-group>
        </el-col>
        <!--<el-col :span="5"><el-radio v-model="isQueryAll" :label="0"></el-radio></el-col>-->
        <!--<el-col :span="5"><el-radio v-model="isQueryAll" :label="1"></el-radio></el-col>-->
        <el-col :span="24" style="height:500px;overflow-y: auto; margin-top: 20px">
          <el-tree :data="treeData"
                   :props="defaultProps"
                   :load="loadNode"
                   lazy
                   show-checkbox
                   ref="listTree"
                   node-key="categoryId"
                   class="listTree noScroll"
                   :default-checked-keys="treeSelectData"
                   :style="treeHeight"
                   :filter-node-method="filterNodeMethod"
                   @check-change="handleCheckChange">
          </el-tree>
        </el-col>
      </el-row>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="cancelDialogDataHandle">取 消</el-button>
        <el-button type="primary"
                   @click="submmitTreeSelectData">确 定</el-button>
      </span>
    </el-dialog>
    <!-- editDialog 目录设置弹窗 END -->
  </el-card>
</template>

<script>
import eTable from '@/components/e-table'
import eForm from '@/components/e-form'
import { formOptions, btns } from './control'
import columns from './columns'
import { editFormOptions, editFormRules, editProcessFormOptions } from './form'
import { queryPurchaseBranch, queryDictionary, editDictionary, getQueryItemTrees, queryBranchCategoryList, editCategoryList, modifyPurchaseBranch } from '@/api/admin.api'
export default {
  name: 'procurement-branch-manager',
  components: {
    eTable,
    eForm
  },
  props: {},
  data () {
    return {
      formOptions,
      searchLabelWidth: '100px',
      btns,
      columns,
      editForm: editFormOptions,
      editFormLabelWidth: '130px',
      editFormRules,
      // 编辑框是否展示
      editInfoDialogShow: false,
      editProcessDialogShow: false,
      editCatalogueDialogShow: false,
      // 编辑框类型 0:新增;1:修改;
      editDialogType: 0,
      // 编辑框表单数据
      dialogFormCurrent: {},
      // 查询表单
      searchFormData: {},
      // 控制区高度
      controlHeight: 0,
      // 表单数据
      tableData: [],
      // 分页数据
      pageData: {
        // 当前分页
        pageNum: 1,
        // 分页条数
        pageSize: 10,
        // 数据总数
        total: 0
      },
      // 流程数据字典
      processData: [],
      // 修改的流程数据字典
      processChangedData: [],
      // 目录设置树节点
      treeData: [],
      // 目录设置默认选中的树节点
      treeSelectData: [],
      // 树配置项
      defaultProps: {
        children: 'children',
        label: 'label',
        check: false,
        isLeaf: 'leaf',
        categorylevel: 1,
        categoryId: 'id'
      },
      // 查询范围   0 仅显示已设置  1显示全部
      isQueryAll: 0,
      submmitSelectTree: [],
      nodeTemp: []
    }
  },
  computed: {
    // 表单实例
    dialogForm () {
      return this.$refs.dialogForm
    },
    // 树实例
    // treeRef() {
    //   return this.$refs['listTree']
    // },
    //表格最大高度
    tableMaxHeight () {
      return window.innerHeight - this.controlHeight - 160
    },
    // 树的高度
    treeHeight () {
      return {
        'height': '300',
        'overflowY': 'scroll'
      }
    },
    // 编辑框标题
    editDialogTitle () {
      if (this.editDialogType === 0) {
        return '修改基本信息'
      }
      else if (this.editDialogType === 1) {
        return '编辑流程信息'
      }
      else if (this.editDialogType === 2) {
        return '目录设置'
      }
      return ''
    }
  },
  created () {
    this.getTableData()
    this.getLabelData()
  },
  mounted () { 
    // console.log(this.nodeTemp)
   },
  methods: {
    /**
     * @functionName changePageSize
     * @param {Number} size 分页条数
     * @description 修改分页条数
     * @author 张航
     * @date 2020-09-08 17:57:06
     * @version V1.0.0
     */
    changePageSize (size) {
      this.pageData.pageSize = size
      this.getTableData()
    },
    /**
     * @functionName changePageCurrent
     * @param {Number} current 当前分页
     * @description 修改当前分页
     * @author 张航
     * @date 2020-09-08 18:02:03
     * @version V1.0.0
     */
    changePageCurrent (current) {
      this.pageData.pageNum = current
      this.getTableData()
    },
    /**
     * @functionName refreshPageCurrent
     * @description 重置当前分页
     * @author 张航
     * @date 2020-09-22 10:45:57
     * @version V1.0.0
     */
    refreshPageCurrent () {
      this.pageData.pageNum = 1
      this.getTableData()
    },
    /**
     * @functionName getTableData
     * @description 获取表格数据
     * @author 张航
     * @date 2020-09-08 17:59:45
     * @version V1.0.0
     */
    getTableData () {
      // 获取去列表数据
      queryPurchaseBranch(this.searchData).then(res=>{
        this.tableData = res.records
        this.pageData.total = res.total
      })
    },
    /**
     * @functionName getTableData
     * @description 获取标签选项数据
     * @author 张文韬
     * @date 2020-10-23 18:17:34
     * @version V1.0.0
     */
    getLabelData () {
      //采购方式
      const params1 = { dictionaryType: 'purchase_type' }
      queryDictionary(params1).then(res=>{
        // console.log(res)
        res.map((item, index) => {
          const optionObj = {}
          optionObj.label = item.optional1
          optionObj.value = item.dictionaryKey1
          this.$set(editFormOptions[2].options, index, optionObj)
        })
      })
      // 采购类型
      const parmas2 = { dictionaryType: 'purchase_method' }
      queryDictionary(parmas2).then(res=>{
        res.map((item, index) => {
          const optionObj = {}
          optionObj.label = item.optional1
          optionObj.value = item.dictionaryKey1
          // this.$set(this.formOptions[0].options, index, optionObj)
          this.$set(editFormOptions[4].options, index, optionObj)
        })
      })
      // 商品来源
      const parmas3 = { dictionaryType: 'goods_source' }
      queryDictionary(parmas3).then(res=>{
        res.map((item, index) => {
          const optionObj = {}
          optionObj.label = item.optional1
          optionObj.value = item.dictionaryKey1
          // this.$set(this.formOptions[0].options, index, optionObj)
          this.$set(editFormOptions[10].options, index, optionObj)
        })
      })
    },
    // 获取当前展示目录
    getCurrentCategory () {
      // 获取全部目录
      // getQueryItemTrees({ categorylevel: '1' }).then((res) => {
      //   // 获取当前选中目录
      //   queryBranchCategoryList(this.dialogFormCurrent.id).then(res2 => {
      //     let temp = []
      //     res2.map(item => {
      //       temp.push(item.categoryId)
      //     })
      //     console.log(res2);
          
      //     this.submmitSelectTree = res2
      //     this.treeSelectData = temp
      //     let newArr = []
      //     // 当前是否全部展示目录
      //     if (this.isQueryAll === 0) {
      //       newArr = this.getCommonTreeDatas(res, temp)
      //     }
      //     else {
      //       newArr = this.formatTreeNodeData(res)
      //     }
      //     this.treeData = newArr
      //   }).catch(err => {
      //     // 处理当前选中返回异常
      //     if (this.isQueryAll === 1) {
      //       this.treeData = this.formatTreeNodeData(res)
      //     }
      //     else {
      //       this.treeData = []
      //     }
      //   })
      // })
      
      // 两个请求404状态处理异常 重写 
      // 获取当前选中目录
      queryBranchCategoryList(this.dialogFormCurrent.id).then(res2 => {
        // let temp = []
        // res2.map(item => {
        //   temp.push(item.categoryId)
        //   if (item.categoryParents) {
        //     const arr = item.categoryParents.split(',')
        //     arr.forEach(cur=>{
        //       temp.push(cur)
        //     })
        //   }
        // })
        // temp = [...new Set(temp)]
        this.submmitSelectTree = res2
        this.treeSelectData = this.dataFlat(res2)
        this._getQueryItemTrees()
      }).catch(err => {
        this.submmitSelectTree = []
        this.treeSelectData = []
        this._getQueryItemTrees()
      })

    },
    // 拆分上边方法
    _getQueryItemTrees(){
      getQueryItemTrees({ categorylevel: '1' }).then((res) => {
        let newArr = []
        // 当前是否全部展示目录
        if (this.isQueryAll === 0) {
          newArr = this.getCommonTreeDatas(res, this.treeSelectData)
        }
        else {
          newArr = this.formatTreeNodeData(res)
        }
        this.treeData = newArr
      }).catch(err => {
          // 处理当前选中返回异常
          if (this.isQueryAll === 1) {
            this.treeData = this.formatTreeNodeData(res)
          }
          else {
            this.treeData = []
          }
        })
    },
    // 懒加载弹出框的tree
    loadNode (node, resolve) {
      // const selectedArr = this.treeSelectData
      const selectedArr = this.dataFlat(this.submmitSelectTree)
      
      if (node.level === 1 || node.level === 2) {
        getQueryItemTrees({ categorylevel: node.data.categorylevel, categoryId: node.data.categoryId }).then((res) => {
          let secArr = []
          if (this.isQueryAll === 0) {
            secArr = this.getCommonTreeDatas(res, selectedArr, node.level === 1?false:true)
          }
          else {
            secArr = this.formatTreeNodeData(res,node.level === 1?false:true)
            this.$refs['listTree'].$nextTick().then(() =>{
              this.$refs['listTree'].filter(selectedArr);
            })
          }
          return resolve(secArr)
        })
      }
      // 1,2合并啦
      
      // if (node.level === 2) {
      //   getQueryItemTrees({ categorylevel: node.data.categorylevel, categoryId: node.data.categoryId }).then((res) => {
      //     let thrArr = []
      //     if (this.isQueryAll === 0) {
      //       thrArr = this.getCommonTreeDatas(res, selectedArr, true)
      //     }
      //     else {
      //       thrArr = this.formatTreeNodeData(res, true)
      //       this.$refs['listTree'].$nextTick().then(() =>{
      //         this.$refs['listTree'].filter(selectedArr);
      //       })
      //     }
      //     return resolve(thrArr)
      //   })
      // }
    },
    /**
     * @functionName getTableData
     * @description 编辑流程信息
     * @author 张文韬
     * @date 2020-10-13 15:37:41
     * @version V1.0.0
     */
    handleEditProcessInfo (data) {
      this.dialogFormCurrent = { ...data }
      // 编辑流程弹出框编辑项
      const parmas4 = { dictionaryType: 'purchase_branch_process',dictionaryKey1: data.id }
      queryDictionary(parmas4).then(res => {
        res.map((item, index) => {
          this.processData = res
          this.openDialog(1)
        })
      }).catch(err => {
        this.$message({
          message: '未获取到流程信息字段',
          type: 'warning'
        })
      })
    },
    // 提交编辑流程信息
    submmitEditProcess() {
      const process = this.processChangedData
      if (process.length > 0){
        process.map((item) => {
          const pramas = {
            id: item.id,
            dictionaryKey3: item.dictionaryKey3,
            optional2: item.optional2
          }
          editDictionary(pramas).then(res => {
            this.closeDialog()
            this.$message({
              message: '保存成功',
              type: 'success'
            })
          })
        })
      }
      else {
        this.closeDialog()
        this.$message({
          message: '未进行操作',
          type: 'warning'
        })
      }
    },
    // 提交目录配置数据
    submmitTreeSelectData () {
      const params = {
        branchId: this.dialogFormCurrent.id,
        categoryList: this.submmitSelectTree,
        categoryId: ''
      }
      editCategoryList(params).then(res => {
        this.closeDialog()
        this.$message({
          message: '保存成功',
          type: 'success'
        })
      })
    },

    // 获取两个树节点数组的交集
    // 返回交集完整数据数组
    // dataSource: 返回的完整数据数组 selectData：选中id的数组
    getCommonTreeDatas (dataSource, selectData, isLeaf = false) {
      let temp = []
      dataSource.map(item => {
        selectData.map(item2 => {
          if (item.id === item2) {
            const obj = {}
            obj.label = item.category_name
            obj.categoryId = item.id
            obj.categorylevel = item.category_level + 1
            obj.check = item.check
            if (isLeaf === true) {
              obj.leaf = true
            }
            temp.push(obj)
          }
        })
      })
      return temp
    },
    // 初始化设置树节点数据
    formatTreeNodeData (data, isLeaf = false) {
      let temp = []
      data.map(item => {
        const obj = {}
        obj.label = item.category_name
        obj.categoryId = item.id
        obj.categorylevel = item.category_level + 1
        obj.check = item.check
        obj.leaf = isLeaf
        temp.push(obj)
      })
      return temp
    },
    // 设置流程信息
    switchProcessChange(data){
      let selectDatas = this.processChangedData
      selectDatas.map((item, index) => {
        if (item.id === data.id) {
          selectDatas.splice(index, 1)
        }
      })
      selectDatas.push(data)
      this.processChangedData = selectDatas
    },

    /**
     * @functionName saveDialogData
     * @description 保存弹框数据
     * @author 张航
     * @date 2020-09-08 18:15:14
     * @version V1.0.0
     */
    saveDialogDataHandle () {
      // console.log(this.dialogForm.formData)
      this.$refs['dialogForm'].handleValidate((valid) => {
        if (!valid) {
          this.$message({
            message: '请检查表单填写内容',
            type: 'warning'
          })
          return
        }
        modifyPurchaseBranch(this.dialogForm.formData).then(res => {
          // console.log(res)
          this.dialogForm.handleRefresh()
          this.closeDialog()
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.refreshPageCurrent()
        })
      })
    },

    /**
     * @functionName cancelDialogData
     * @description 取消保存弹框数据
     * @author 张航
     * @date 2020-09-08 18:17:11
     * @version V1.0.0
     */
    cancelDialogDataHandle () {

      this.closeDialog()
    },

    // 处理切换查询范围
    handleSelectQueryAll (data) {
      this.isQueryAll = data
      this.getCurrentCategory()
    },

    // 过滤处理
    filterNodeMethod (value, data, node) {
      for (let i = 0;i < value.length; i ++) {
        if (value[i] === data.categoryId) {
          this.$refs['listTree'].setChecked(data.categoryId, true, false)
          return true
        }
      }
      this.$refs['listTree'].setChecked(data.categoryId, false, false)
      return true
    },

    /**
     * @functionName getTableData
     * @description 修改基本信息
     * @author 张文韬
     * @date 2020-10-13 15:37:41
     * @version V1.0.0
     */
    resetBasicInfo (data) {
      // console.log(data)
      this.dialogFormCurrent = { ...data }
      this.openDialog(0)
    },

    /**
     * @functionName getTableData
     * @description 目录设置
     * @author 张文韬
     * @date 2020-10-13 15:37:41
     * @version V1.0.0
     */
    handleCatalogueSetting (data) {
      this.dialogFormCurrent = { ...data }
      this.handleSelectQueryAll(0)
      // 获取当前选中目录
      queryBranchCategoryList(this.dialogFormCurrent.id).then(res2 => {
        // let temp = []
        // res2.map(item => {
        //   temp.push(item.categoryId)
        //   if (item.categoryParents) {
        //     const arr = item.categoryParents.split(',')
        //     arr.forEach(cur=>{
        //       temp.push(cur)
        //     })
        //   }
        // })
        // temp = [...new Set(temp)]

        this.submmitSelectTree = res2
        this.treeSelectData = this.dataFlat(res2)
        this.openDialog(2)
      }).catch(err=>{
        if (err.code===-2) {
          this.openDialog(2)
        }
      })
    },
    // 选择树节点
    handleCheckChange (data,checked) {
      // console.log(this.$refs['listTree'].getCheckedNodes(false,true));
      // const ids = this.$refs['listTree'].getCheckedKeys()
      // const pids = this.$refs['listTree'].getHalfCheckedKeys()
      // this.submmitSelectTree = [
      //   ...ids,
      //   ...pids
      // ]
      if (data.leaf) {
        let temp = {
          categoryId: data.categoryId
        }
        let currentNode = this.$refs['listTree'].getNode(data)
        let parentNode = currentNode.parent
        let pparentNode = parentNode.parent
        temp.categoryParents = [ parentNode.key, pparentNode.key ].toString()
        if (!checked) {
          for (let i = 0; i < this.submmitSelectTree.length; i++) {
            const item = this.submmitSelectTree[i];
            if (item.categoryId === temp.categoryId) {
                this.submmitSelectTree.splice(i,1)
                break
            }
          }
        }else{
          this.submmitSelectTree.push(temp)
        }
      }
    },
    // 数组扁平化
    dataFlat(arr){
      let temp = []
        arr.map(item => {
          temp.push(item.categoryId)
          if (item.categoryParents) {
            const arr = item.categoryParents.split(',')
            arr.forEach(cur=>{
              temp.push(cur)
            })
          }
        })
        return [...new Set(temp)]
    },
    /**
     * @functionName openDialog
     * @param {Number} type 编辑框类型;0:新增;1:编辑;
     * @description 打开编辑框
     * @author 张航
     * @date 2020-09-08 11:38:51
     * @version V1.0.0
     */
    openDialog (type = 0) {
      this.editDialogType = type
      if (type === 0) {
        this.editInfoDialogShow = true
      }
      else if (type === 1) {
        this.editProcessDialogShow = true
      }
      else if (type === 2) {
        this.editCatalogueDialogShow = true
      }
    },
    /**
     * @functionName closeDialog
     * @description 关闭编辑框
     * @author 张航
     * @date 2020-09-08 14:27:02
     * @version V1.0.0
     */
    closeDialog () {
      const type = this.editDialogType
      if (type === 0) {
        this.editInfoDialogShow = false
        if (this.dialogForm) {
          this.dialogForm.handleRefresh()
        }
      }
      else if (type === 1) {
        this.editProcessDialogShow = false
      }
      else if (type === 2) {
        this.editCatalogueDialogShow = false
        this.isQueryAll = 0
        this.treeData = []
        this.submmitSelectTree = []
        this.treeSelectData = []
      }
      this.editDialogType = 0
    },
  }
}
</script>
<style lang="scss" >
.box-card {
  margin: 4px;
  height: calc(100vh - 110px);
  .el-card__body {
    padding: 0;
  }
}
.abc-header {
  color: #0000ff;
}
.item-box {
  padding: 5px;
}
.listTree.noScroll{
  overflow-y: hidden!important;
}
.listTree .el-tree-node {
  .is-leaf + .el-checkbox .el-checkbox__inner {
    display: inline-block;
  }

  .el-checkbox__input > .el-checkbox__inner {
    display: none;
  }
}
.dialog-box {
  padding: 0px 20px;
}
</style>
